import React, { Component } from 'react'
import {Table,Button} from 'antd'
import { EditOutlined, DeleteOutlined,ChromeOutlined } from '@ant-design/icons';
import axios from 'axios';

export default class List extends Component {
  state = {
    datalist:[],
    columns:[
      { title: '文章标题', dataIndex: 'title', key: 'title' },
      { title: '文章作者', dataIndex: 'author', key: 'author' },
      {
          title: '文章类别', dataIndex: 'category', key: 'category',
          render:(item)=><div>{item.join("/")}</div>
      },
      {
        title: '操作',
        dataIndex: '',
        key: 'x',
        render: (item) => <div>
          {/* 预览文章 */}
          <Button  shape="circle" icon={<ChromeOutlined />}
          onClick={()=>this.handlePreviewClick(item.id)}/>
          &nbsp;
          {/* 更新文章 */}
          <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={()=>this.handleUpdateClick(item.id)}/>
          &nbsp;
          {/* 删除文章 */}
          <Button type="danger" shape="circle" icon={<DeleteOutlined/>} onClick={()=>this.handleDelClick(item.id)}/>
          </div>
      }
    ]
  }
  render() {
    return (
      <div>
        <Button onClick={this.changePage} type="primary">添加文章</Button>
        <Table columns={this.state.columns} dataSource={this.state.datalist}
          rowKey={item => {
              // console.log(item)
              return item.id
          }} //设置key值
          />
      </div>
    )
  }

  // 获取初始文章
  componentDidMount() {
    axios.get("http://localhost:8000/articles").then(res =>{
      // 低权限用户不能看高权限用户的文章
      var lists = res.data.filter(item =>(
        item.roleType <= JSON.parse(localStorage.getItem("users")).roleType
        )
      )
      // 过滤后赋值
      this.setState({
        datalist:lists
      })
    })
  }
  
  //添加文章
  changePage = () =>{
    this.props.history.push(`/article-manage/create`)
  }
  // 预览文章
  handlePreviewClick = (id) =>{
    this.props.history.push(`/article-manage/preview/${id}`)
  }
  // 更新文章
  handleUpdateClick = (id) =>{
    this.props.history.push(`/article-manage/update/${id}`)
  }
  // 删除文章
  handleDelClick = (id) =>{
    axios.delete(`http://localhost:8000/articles/${id}`).then(res =>{
      // 同步修改datalilst状态，
      this.setState({
      datalist:this.state.datalist.filter(item =>item.id !== id)
      })
    })
  }
}
